<template>
  <div class="content-wrap">
    <table-page
      :fit="true"
      :columns="columns"
      :value="tableData"
      :total="pageTotal"
      :pageNum="tablePageParams.pageNum"
      :pageSize="tablePageParams.pageSize"
      :loading="tableLoading"
      @on-change-page="onChangePage"
      @on-row-dblclick="onRowDblclick"
      :stripe="false"
      size="small"
      :border="false"
      :no-data-text="tableHint"
    >
      <Form slot="search-bar" :model="formCustom" inline ref="formCustom">
        <FormItem prop="meterId">
          <Input type="text" placeholder="表ID" v-model.trim="formCustom.meterId" style="width: 80px" />
        </FormItem>
        <FormItem prop="sector">
          <Select v-model="formCustom.sector" placeholder="次级部门" multiple style="width: 190px">
            <Option v-for="(type, index) in sectorList" :key="index" :value="type.value">{{ type.value }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="meterType">
          <Select v-model="formCustom.meterType" placeholder="表类型" multiple style="width:190px;">
            <Option v-for="(type, index) in meterTypeList" :key="index" :value="type.value">{{ type.value }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="meterGasClass">
          <Select v-model="formCustom.modelNo" placeholder="型号" multiple style="width: 190px">
            <Option v-for="(type, index) in modelList" :key="index" :value="type.value">{{ type.value }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="meterGasClass">
          <Select v-model="formCustom.meterGasClass" placeholder="用气性质" multiple style="width: 120px">
            <Option v-for="(type, index) in gasClassList" :key="index" :value="type.value">{{ type.value }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="installTime">
          <DatePicker
            type="daterange"
            :clearable="false"
            split-panels
            v-model="installTime"
            placeholder="安装时间"
          ></DatePicker>
        </FormItem>
        <FormItem prop="jsTime">
          <DatePicker
            type="daterange"
            :clearable="false"
            split-panels
            v-model="jsTime"
            placeholder="接收时间"
          ></DatePicker>
        </FormItem>
        <FormItem>
          <Select v-model="formCustom.minYear" placeholder="起始" style="width: 80px">
            <Option v-for="(year, index) in startYearSpace" :key="index" :value="year.value">{{
              year.label
            }}</Option> </Select
          >至
          <Select v-model="formCustom.maxYear" placeholder="截至" style="width: 80px">
            <Option v-for="(year, index) in endYearSpace" :key="index" :value="year.value">{{ year.label }}</Option>
          </Select>
        </FormItem>
        <FormItem>
          <Button icon="ios-search" type="info" @click="handleSubmit" :loading="searchLoading">查询</Button>
          <Button icon="ios-refresh" type="primary" @click="handleReset('formCustom')" style="margin-left: 8px"
            >重置</Button
          >
        </FormItem>
      </Form>
    </table-page>
    <edit-form
      :visibile="showModalFlag"
      :formData="currentFormData"
      @handleSave="handleSave"
      @handleCancel="handleEditModalCancel"
    />
    <Modal
      v-model="showTreeFlag"
      class="tree-modal"
      title="详情"
      @on-cancel="onTreeCancel"
      width="96%"
      :styles="{ top: '30px', height: '85%' }"
    >
      <div :is="userAndMeterInfoTpl" :content="meterDetailData" :currentMeterId="currentMeterId"></div>
      <div slot="footer">
        <Button @click="onTreeCancel" ghost>关闭</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import { isEmpty, filter } from 'lodash'
import tableMixin from '@/mixins/table'
import removeParamsNullValue from '@/utils/removeParamsNullValue'
import tableColums from './tableColums'
import { yearSpace } from './yearSpace'
import { createNamespacedHelpers } from 'vuex'
import EditForm from './components/EditForm'
const { mapState, mapActions } = createNamespacedHelpers('meterManageQuery')

export default {
  name: 'MeterManageQuery',
  inject: ['reload'],
  components: {
    EditForm,
    UserAndMeterDetailETree: () => import('@/commons/UserAndMeterDetailETree')
  },
  data() {
    return {
      searchLoading: false,
      modelTit: '',
      showModalFlag: false,
      showTreeFlag: false,
      currentFormData: null,
      formCustom: {
        meterId: undefined,
        sector: undefined,
        meterType: undefined,
        meterGasClass: undefined,
        installBeginTime: undefined,
        installEndTime: undefined,
        jsBeginTime: undefined,
        jsEndTime: undefined,
        minYear: undefined,
        maxYear: undefined
      },
      installTime: undefined,
      jsTime: undefined,
      meterDetailData: null,
      userAndMeterInfoTpl: null
    }
  },
  mixins: [tableMixin],
  computed: {
    ...mapState([
      'tableData',
      'meterTypeList',
      'sectorList',
      'gasClassList',
      'modelList',
      'tableLoading',
      'tablePageParams',
      'tableData',
      'pageTotal',
      'currentMeterId'
    ]),
    columns() {
      return this.renderTableColums()
    },
    tableHint() {
      if (!this.tableData || this.tableData.length < 1) {
        return '暂无数据'
      }
      return ''
    },
    /**
     * @msg: 间隔起始年
     * @param {type}
     * @return: 间隔年份
     */
    startYearSpace() {
      return yearSpace
    },
    endYearSpace() {
      const { minYear } = this.formCustom
      let ret = []
      if (minYear) {
        ret = filter(yearSpace, item => {
          return item.value >= minYear
        })
      }
      return ret
    }
  },
  beforeDestroy() {
    this.clearStore()
  },
  created() {
    this.loadMeterType()
    this.loadGasClass()
    this.loadMeterSector()
    this.loadModel()
  },
  activated() {
    this.loadTableData()
  },
  methods: {
    ...mapActions([
      'loadTableData',
      'loadMeterType',
      'loadGasClass',
      'loadMeterSector',
      'loadModel',
      'saveData',
      'loadMeterUtilDetail',
      'changeMeterId',
      'changeTablePageParams',
      'clearStore'
    ]),
    /**
     * 处理区间时间
     * @param  {[type]} date [description]
     * @return {[type]}      [description]
     */
    modifyPickerTime(pickerData = []) {
      let [startDate, endDate] = pickerData
      if (startDate) {
        startDate = dayjs(startDate).format('YYYY-MM-DD')
      } else {
        startDate = undefined
      }
      if (endDate) {
        endDate = dayjs(endDate).format('YYYY-MM-DD')
      } else {
        endDate = undefined
      }
      return [startDate, endDate]
    },
    /**
     * 表格行设置
     * @return {[type]} [description]
     */
    renderTableColums() {
      const lastCloums = {
        title: '操作',
        align: 'center',
        fixed: 'right',
        width: 100,
        render: (h, params) => {
          return h('div', [
            h('Button', {
              props: {
                type: 'text',
                size: 'small',
                customIcon: 'iconfont icon-edit'
              },
              attrs: {
                title: '编辑'
              },
              on: {
                click: () => {
                  this.handleEdit(params.row)
                }
              }
            })
          ])
        }
      }

      return [...tableColums, lastCloums]
    },
    /**
     * 查询
     * @return {[type]} [description]
     */
    handleSubmit() {
      this.searchLoading = true
      const [installBeginTime, installEndTime] = this.modifyPickerTime(this.installTime)
      const [jsBeginTime, jsEndTime] = this.modifyPickerTime(this.jsTime)
      this.formCustom.installBeginTime = installBeginTime
      this.formCustom.installEndTime = installEndTime
      this.formCustom.jsBeginTime = jsBeginTime
      this.formCustom.jsEndTime = jsEndTime
      this.changeTablePageParams({
        pageNum: 1
      })
      this.loadAjax()
    },
    /**
     * 重置搜索
     * @return {[type]} [description]
     */
    handleReset(form) {
      this.$refs[form].resetFields()
      this.formCustom = {
        meterId: undefined,
        sector: undefined,
        meterType: undefined,
        meterGasClass: undefined,
        installBeginTime: undefined,
        installEndTime: undefined,
        jsBeginTime: undefined,
        jsEndTime: undefined,
        minYear: null,
        maxYear: null
      }
      this.installTime = undefined
      this.jsTime = undefined
      this.changeTablePageParams({
        pageNum: 1
      })
      this.loadAjax()
    },
    /**
     * 获取表格数据
     * @return {[type]} [description]
     */
    loadAjax() {
      this.loadTableData(removeParamsNullValue(this.formCustom))
      this.searchLoading = false
    },
    /**
     * 表格数据编辑
     * @param  {[type]} row [description]
     * @return {[type]}     [description]
     */
    handleEdit(row = {}) {
      if (!isEmpty(row)) {
        this.showModalFlag = true
        this.modelTit = '编辑'
        this.currentFormData = {
          ...this.formItem,
          ...row
        }
      } else {
        this.$Notice.warning({
          title: '提示信息',
          desc: '没有要编辑的数据'
        })
      }
    },
    /**
     * 保存数据
     * @return {[type]} [description]
     */
    handleSave(params) {
      this.handleEditModalCancel()
      this.saveData(params)
      this.loadAjax()
    },
    handleEditModalCancel() {
      this.showModalFlag = false
    },
    onTreeCancel() {
      this.showTreeFlag = false
      this.meterDetailData = null
      this.userAndMeterInfoTpl = null
    },
    /**
     * @msg: 双击行数据
     * @param {type}
     * @return:
     */
    async onRowDblclick(row = {}, index) {
      this.$Loading.start()
      const { meterId } = row
      this.changeMeterId(meterId)
      const _ret = await this.loadMeterUtilDetail()
      if (_ret.date) {
        this.$Loading.finish()
        this.meterDetailData = _ret.date
        this.userAndMeterInfoTpl = 'UserAndMeterDetailETree'
        this.showTreeFlag = true
      }
    },
    onChangePage(page, pageSize) {
      this.changeTablePageParams({
        pageNum: page,
        pageSize: pageSize
      })
      this.loadAjax()
    }
  }
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>
